﻿using FySystem.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FySystem.Net.LSTP
{
    public class LSTPWebResponse
    {
        public byte[] RequestId { get; internal set; }
        public int? Status { get; internal set; }
        public string Error { get; internal set; }
        public CSon Body { get; internal set; }

        /// <summary>
        /// 向流写入错误消息
        /// </summary>
        /// <param name="status"></param>
        /// <param name="error"></param>
        public void WriteError(int status, string error)
        {
            try
            {
                if (status <= 0)
                    throw new Exception("status必须大于0");

                Status = status;
                Error = error;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 向流写入内部错误
        /// </summary>
        internal void WriteInterError(int status, string error)
        {
            try
            {
                Status = status;
                Error = error;
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 向流写入数据
        /// </summary>
        /// <param name="data"></param>
        public void Write(CSon data)
        {
            Body = data;
        }

        internal CSon ToResponse()
        {
            CSon res = new CSon(CSon.CSonTypes.CObject);
            try
            {
                //将请求id加入结果集
                res.Add("requestId", RequestId);

                //状态
                res.Add("status", Status);

                //错误
                res.Add("error", Error);

                //数据
                res.Add("body", Body == null ? CSon.CSonObjectNull : Body);
            }
            catch (Exception)
            {
                throw;
            }
            return res;
        }
    }
}
